SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

alter  FUNCTION f_finEndSubMAmt (
  @ABvouyearmonth INT,
  @AEvouyearmonth INT,
  @filid int,
  @moneyid int,
  @binder INT,
  @check INT
) RETURNS TABLE
AS
RETURN(
  SELECT W.subjectid, W.moneyid, K.subCode, vouyearmonth
   , MDebit, MCredit 
   , MDcDebit, MDcCredit 
  FROM
  (
    SELECT subjectid, moneyid, vouyearmonth
      , sum(Debitamt) AS MDebit, sum(Creditamt) AS MCredit 
      , sum(DcDebitamt) AS MDcDebit, sum(Creditamt) AS MDcCredit 
      FROM
    (
      SELECT B.subjectid, b.moneyid, A.vouyearmonth, B.Debitamt, B.Creditamt, B.DcDebitamt, B.DcCreditamt  
        FROM tfb_Voucher A LEFT JOIN tfb_Voucherdtl B ON B.voucherid = A.voucherid
        WHERE A.voucherid > 0 
          AND (A.bstate=1 OR @check=1)
          AND (A.binder_by is not null OR @binder=1)
          And (a.filid=@filid or @filid=-99)
          and (b.moneyid=@moneyid or @moneyid=-99)
          AND A.vouyearmonth >= @ABvouyearmonth AND A.vouyearmonth <= @AEvouyearmonth
    ) AS V GROUP BY subjectid, moneyid, vouyearmonth
  ) AS W
  LEFT JOIN tfd_Subject K ON K.subjectid = W.subjectid
)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

